// pages/ticket/ticket.js
var app = getApp();
var clickCount = 0; // 点击第三方票券的次数
const Format = require("../../utils/time.js");
var QR = require("../../utils/qrcode.js");
var getTicket = function(that) {
    app.getApi.getProducts("POST", {
        isCanUsed: that.data.navIndex,
        pageNumber: that.data.pageNumber,
        pageSize: 10,
        unionId: app.globalData.unionId,
        method: "opg.eventGroupGetByUnionId.ticket",
        sortType: 1,
        sortKey: 1
    }).then(data => {
        var list = that.data.items;
        var size = that.setCanvasSize();

        if (data.data.result.length > 0) {
            for (let i = 0; i < data.data.result.length; i++) {
                data.data.result[i].startTimeStr = data.data.result[i].startTimeStr.substring(0, 16)
                data.data.result[i].endTimeStr = data.data.result[i].endTimeStr.substring(0, 16)
                var startTime = data.data.result[i].startTimeStr;
                var ssdat = new Date(startTime.substring(0, 4), parseInt(startTime.substring(5, 7)) - 1, startTime.substring(8, 10))
                var stateMonth = Format.getMonth(parseInt(startTime.substring(5, 7)), that.data.isChinese),
                    stateDay = parseInt(startTime.substring(8, 10)) + (that.data.isChinese ? '日 ' : ' '),
                    stateWeek = Format.getWeek(ssdat.getDay(), that.data.isChinese),
                    stateHours = (ssdat.getHours() > 12 ? 24 - ssdat.getHours() : ssdat.getHours() == 0 ? 12 : ssdat.getHours()) + (startTime.substring(13, 16) + (ssdat.getHours() >= 12 ? "pm" : "am"));
                data.data.result[i].startTimeStr = stateMonth + stateDay + stateWeek + " " + stateHours
                var endTime = data.data.result[i].endTimeStr;
                var endat = new Date(endTime.substring(0, 4), parseInt(endTime.substring(5, 7)) - 1, endTime.substring(8, 10))
                var endMonth = Format.getMonth(parseInt(endTime.substring(5, 7)), that.data.isChinese),
                    endDay = parseInt(endTime.substring(8, 10)) + (that.data.isChinese ? '日 ' : ' '),
                    endWeek = Format.getWeek(endat.getDay(), that.data.isChinese),
                    endHours = (endat.getHours() > 12 ? 24 - endat.getHours() : endat.getHours() == 0 ? 12 : endat.getHours()) + (endTime.substring(13, 16) + (endat.getHours() >= 12 ? "pm" : "am"));

                if ((data.data.result[i].endTime - data.data.result[i].startTime) / 86400000 >= 1) {
                    data.data.result[i].endTimeStr = endMonth + endDay + endWeek + " " + endHours
                } else {
                    data.data.result[i].endTimeStr = endHours
                }
                list.push(data.data.result[i])
            }
        }

        that.setData({
            itemArr: data.data.result,
            loadMore: true,
            size: size,
            onLoadMore: true
        })
        if (Math.ceil(data.data.totalCount / 10) == that.data.pageNumber) {
            that.setData({
                isAll: true
            })
        }
        that.setData({
            items: list,
            loadMore: false,
            totalCount: data.data.totalCount
        })
        if (that.data.pageNumber == 1) {
            that.Count()
        }
        wx.stopPullDownRefresh()
    })
}
var getTicketList = function(that, eventId, type) { //查看票
    app.getApi.getProducts("POST", {
        isCanUsed: that.data.navIndex,
        pageNumber: that.data.ftIndex,
        type: type,
        pageSize: 5,
        // unionId: app.globalData.unionId,
        eventId: eventId,
        method: "opg.ticketListGetByEventId.ticket",
        sortType: 1,
        sortKey: 1
    }).then(data => {
        var list = that.data.codeList;
        var size = that.data.size;
        if (data.data.result.length > 0) {
            for (let i = 0; i < data.data.result.length; i++) {
                list.push(data.data.result[i])
            }
            that.createQrCode(list[0].number, "mycanvas0", that.data.size.w, that.data.size.h);
        }

        that.setData({
            codeList: list
        })


        if (Math.ceil(data.data.totalCount / 10) == that.data.pageNumber) {
            that.setData({
                isAll: true
            })
        }
        that.setData({
            totalCount: data.data.totalCount
        })
        if (that.data.pageNumber == 1) {
            that.Count()
        }
    })
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navIndex: 1,
        codeShow: false, //是否查看票券
        current: 0,
        pageNumber: 1,
        hidden: false, //没有更多
        loadMore: false, //是否显示加载更多
        onLoadMore: false, //首次加载完成
        isAll: false,
        size: {},
        items: [],
        totalCount: 0,
        ftIndex: 1,
        codeList: [],
        lookEventId: "", //查看活动的id
        lookEventType: "", //查看票的类型
        opgCode: "", //opg票券
        thirdparty: true //第三方票券显示
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this
        var size = this.setCanvasSize()
        var that = this

        that.setData({
            isChinese: wx.getStorageSync("isChinese"),
            size: size
        })
        wx.setNavigationBarTitle({
            title: that.data.isChinese ? "我的票劵" : "My Tickets"
        })
        getTicket(that)
        var res = wx.getSystemInfoSync();
        var typeWidth = wx.getStorageSync("isChinese") ? 16 : 38
        that.setData({
            eventWidth: res.windowWidth - 120 - typeWidth
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    setCanvasSize: function() {
        var size = {};
        try {
            var res = wx.getSystemInfoSync();
            var scale = 750 / 686; //不同屏幕下canvas的适配比例；设计稿是750宽
            var width = res.windowWidth / scale / 2;
            var height = width; //canvas画布为正方形
            size.w = width;
            size.h = height;
            console.log(res.windowWidth)
        } catch (e) {
            // Do something when catch error

        }
        return size;
    },
    bindchange(e) {

        this.createQrCode(this.data.codeList[e.detail.current].number, "mycanvas" + e.detail.current, this.data.size.w, this.data.size.h);
        // if()
    },
    createQrCode: function(url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        var that = this
        QR.qrApi.draw(url, canvasId, cavW, cavH);

        setTimeout(function() {
            wx.canvasToTempFilePath({
                width: 350,
                height: 350,
                destWidth: 350,
                destHeight: 350,
                canvasId: canvasId,
                success: function(res) {
                    that.setData({
                        opgCode: res.tempFilePath
                    })

                },
                fail(res) {}
            })
        }, 300)

    },
    Count() {
        var totalCount = this.data.totalCount;
        // var totalCount = 8;
        var newCountList = []
        for (let j = 1; j < totalCount + 1; j++) {
            newCountList.push(j)
        }
        var a_len = newCountList.length;
        var result = [];
        for (var i = 0; i < a_len; i += 5) {
            result.push(newCountList.slice(i, i + 5));
        }
        var newArr = []
        for (let a = 0; a < result.length; a++) {
            if (result[a].length == 1) {
                newArr.push(result[a][0])
            } else {
                newArr.push(result[a][0] + "-" + result[a][result[a].length - 1])
            }
        }
        this.setData({
            countArr: newArr
        })
    },

    nav(e) {
        var that = this
        that.setData({
            navIndex: e.currentTarget.dataset.index,
            pageNumber: 1,
            loadMore: false,
            onLoadMore: false,
            items: [],
            hidden: false,
            isAll: false
        })
        getTicket(that)

    },
    footerC(e) {
        this.setData({
            ftIndex: Number(e.currentTarget.dataset.index) + 1,
            codeShow: true,
            codeList: [],
            current: 0,
        })
        getTicketList(this, this.data.lookEventId, this.data.lookEventType)
    },
    close() {
        this.setData({
            codeShow: false
        })
    },
    look(e) {
        var that = this
        that.setData({
            codeShow: true,
            codeList: [],
            ftIndex: 1,
            lookEventId: e.currentTarget.dataset.id,
            lookEventType: e.currentTarget.dataset.type
        })
        getTicketList(that, e.currentTarget.dataset.id, e.currentTarget.dataset.type)


    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onReachBottom() {
        var that = this
        if (!that.data.isAll && that.data.onLoadMore) {
            that.setData({
                pageNumber: that.data.pageNumber + 1,
                loadMore: true

            })
            getTicket(that)
        } else {
            that.setData({
                hidden: true
            })
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    thirClick(e) { //点击第三方票券
        clickCount++
        if (clickCount == 3) {
            this.setData({
                thirdparty: false
            })
            clickCount = 0
        }
        this.createQrCode(e.currentTarget.dataset.number, "mycanvas" + e.currentTarget.dataset.index, this.data.size.w, this.data.size.h);
    },
    opgClick(e) { //点击opg票券
        // if()
        this.setData({
            thirdparty: true
        })
        this.createQrCode(e.currentTarget.dataset.number, "mycanvas" + e.currentTarget.dataset.index, this.data.size.w, this.data.size.h);
    },
    onPullDownRefresh: function() {
        this.setData({
            navIndex: this.data.navIndex,
            pageNumber: 1,
            loadMore: false,
            onLoadMore: false,
            items: [],
            hidden: false,
            isAll: false
        })
        this.onLoad()
    },
})